package com.mall4jcola.cloud.auth.executor.query;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.cola.dto.Response;
import com.alibaba.cola.exception.ExceptionFactory;
import com.mall4jcola.cloud.auth.model.UserAuthEntity;
import com.mall4jcola.cloud.auth.model.UserLoginInfo;
import com.mall4jcola.cloud.constant.IdentityTypeEnum;
import com.mall4jcola.cloud.userinfo.gateway.UserInfoQueryGateway;
import lombok.AllArgsConstructor;
import lombok.NonNull;
import org.springframework.stereotype.Component;

import javax.validation.constraints.NotBlank;

/**
 * 账户校验执行器
 *
 * @author hmxchen
 */
@Component
@AllArgsConstructor
public class AccountVerificationQryExe {

    private final UserInfoQueryGateway userInfoQueryGateway;

    public Response execute(@NotBlank(message = "账号类型不可为空") String identityType,
                            @NotBlank(message = "凭证不可为空") String credential,
                            @NonNull UserLoginInfo userLoginInfo) {
        UserAuthEntity userAuthEntity = userLoginInfo.getUserAuthEntity();
        if(userAuthEntity == null||!identityType.equals(userAuthEntity.getIdentityType())){
            throw ExceptionFactory.bizException("该账户不存在");
        }
        switch (IdentityTypeEnum.convert(identityType)) {
            case WETCHAT:
                break;
            case PHONE_NO_CODE:
            case EMAIL:
                if (!userAuthEntity.getCredential().equals(credential)) {
                    throw ExceptionFactory.bizException("验证码错误或已失效");
                }
                break;
            case SYS_PWD:
            case PHONE_NO_PWD:
                //对Credential加密
                if (!userAuthEntity.getCredential().equals(SecureUtil.md5(credential))) {
                    throw ExceptionFactory.bizException("密码错误");
                }
                break;
            default:
                throw ExceptionFactory.bizException("当前不支持其它的登录方式");
        }
        //   验证通过后，设置用户基本信息
        userLoginInfo.setUserInfoEntity(userInfoQueryGateway.getByUserId(userLoginInfo.getUserId()));
        return Response.buildSuccess();
    }
}
